package com.wnhz.work.yz.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.wnhz.work.yz.MainActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.activity.ShowImageDetail;
import com.wnhz.work.yz.activity.YanShou2FaActivity;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.Home1OrderBean;
import com.wnhz.work.yz.bean.OrderImgBean;
import com.wnhz.work.yz.constant.Constants;
import com.wnhz.work.yz.utils.BroadCastReceiverUtil;
import com.wnhz.work.yz.utils.LogUtil;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.pull.PullLoadMoreRecyclerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by admin on 2017/6/21.
 */
public class Home1Order extends Fragment implements BroadCastReceiverUtil.OnReceiveBroadcast {
    private View view;
    //, headview;
    private MainActivity activity;
    private PullLoadMoreRecyclerView recycler;
    private RecyclerView head;
    private BroadcastReceiver broadcastReceiver;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home1_home_order, container, false);
        activity = (MainActivity) getActivity();
        //  headview = inflater.inflate(R.layout.fragment_home1_home_order_head, container, false);
        broadcastReceiver = BroadCastReceiverUtil.registerBroadcastReceiver(getContext(), new String[]{ Constants.LOGO_SUCCESS}, Home1Order.this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        recycler = (PullLoadMoreRecyclerView) view.findViewById(R.id.recycler);
        head = (RecyclerView) view.findViewById(R.id.head);
        recycler.setLinearLayout();
        loadadapter = new BaseRVAdapter(activity, list) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_home1;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                holder.getView(R.id.jiedan).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        activity.showDialogv7("是否接单？", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                jiedan(list.get(position).getOrderid(), position);
                            }
                        });
                    }
                });

                if (list.get(position).getJiedan() == 1) {
                    holder.getView(R.id.jiedan).setVisibility(View.GONE);
                } else {
                    holder.getView(R.id.jiedan).setVisibility(View.VISIBLE);
                }


                //
                ImageLoader.getInstance().displayImage(list.get(position).getHeadimg(), holder.getImageView(R.id.head));
                holder.setTextView(R.id.name, list.get(position).getRealname());
                holder.setTextView(R.id.project_name, list.get(position).getProject_name());
                holder.setTextView(R.id.total, "总套数：" + list.get(position).getAll_nums() + "套");
                holder.setTextView(R.id.hetonghao, "合同编号：" + list.get(position).getBudget_no());
                holder.setTextView(R.id.price, "￥" + list.get(position).getAmount() + "元");
                holder.setTextView(R.id.time, list.get(position).getStart_time());
                /////
                ImageView img1 = holder.getImageView(R.id.img1);
                LinearLayout line2 = holder.getView(R.id.line2);
                ImageView img2_1 = holder.getImageView(R.id.img2_1);
                ImageView img2_2 = holder.getImageView(R.id.img2_2);
                LinearLayout line3 = holder.getView(R.id.line3);
                ImageView img3_1 = holder.getImageView(R.id.img3_1);
                ImageView img3_2 = holder.getImageView(R.id.img3_2);
                ImageView img3_3 = holder.getImageView(R.id.img3_3);
                RecyclerView line4 = holder.getView(R.id.line4);

                ////
                List<String> img = list.get(position).getImg();
                switch (img.size()) {
                    case 0:
                        img1.setVisibility(View.GONE);
                        line2.setVisibility(View.GONE);
                        line3.setVisibility(View.GONE);
                        line4.setVisibility(View.GONE);
                        break;
                    case 1:
                        img1.setVisibility(View.VISIBLE);
                        line2.setVisibility(View.GONE);
                        line3.setVisibility(View.GONE);
                        line4.setVisibility(View.GONE);
                        ImageLoader.getInstance().displayImage(list.get(position).getImg().get(0), img1);
                        img1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                Intent intent = new Intent(activity, ShowImageDetail.class);
                                intent.putStringArrayListExtra("paths", (ArrayList<String>) list.get(position).getImg());
                                intent.putExtra("index", 0);
                                startActivity(intent);
                            }
                        });

                        break;
                    case 2:
                        img1.setVisibility(View.GONE);
                        line2.setVisibility(View.VISIBLE);
                        line3.setVisibility(View.GONE);
                        line4.setVisibility(View.GONE);
                        ImageLoader.getInstance().displayImage(list.get(position).getImg().get(0), img2_1);
                        ImageLoader.getInstance().displayImage(list.get(position).getImg().get(1), img2_2);
                        img2_1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                Intent intent = new Intent(activity, ShowImageDetail.class);
                                intent.putStringArrayListExtra("paths", (ArrayList<String>) list.get(position).getImg());
                                intent.putExtra("index", 0);
                                startActivity(intent);
                            }
                        });
                        img2_2.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                Intent intent = new Intent(activity, ShowImageDetail.class);
                                intent.putStringArrayListExtra("paths", (ArrayList<String>) list.get(position).getImg());
                                intent.putExtra("index", 1);
                                startActivity(intent);
                            }
                        });
                        break;
                    case 3:
                        img1.setVisibility(View.GONE);
                        line2.setVisibility(View.GONE);
                        line3.setVisibility(View.VISIBLE);
                        line4.setVisibility(View.GONE);
                        ImageLoader.getInstance().displayImage(list.get(position).getImg().get(0), img3_1);
                        ImageLoader.getInstance().displayImage(list.get(position).getImg().get(1), img3_2);
                        ImageLoader.getInstance().displayImage(list.get(position).getImg().get(2), img3_3);
                        img3_1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                Intent intent = new Intent(activity, ShowImageDetail.class);
                                intent.putStringArrayListExtra("paths", (ArrayList<String>) list.get(position).getImg());
                                intent.putExtra("index", 0);
                                startActivity(intent);
                            }
                        });
                        img3_2.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                Intent intent = new Intent(activity, ShowImageDetail.class);
                                intent.putStringArrayListExtra("paths", (ArrayList<String>) list.get(position).getImg());
                                intent.putExtra("index", 1);
                                startActivity(intent);
                            }
                        });
                        img3_3.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                Intent intent = new Intent(activity, ShowImageDetail.class);
                                intent.putStringArrayListExtra("paths", (ArrayList<String>) list.get(position).getImg());
                                intent.putExtra("index", 2);
                                startActivity(intent);
                            }
                        });

                        break;
                    case 4:
                        img1.setVisibility(View.GONE);
                        line2.setVisibility(View.GONE);
                        line3.setVisibility(View.GONE);
                        line4.setVisibility(View.VISIBLE);
                        line4.setLayoutManager(new GridLayoutManager(activity, 2, LinearLayoutManager.VERTICAL, false));
                        line4.setAdapter(new BaseRVAdapter(activity, list.get(position).getImg()) {
                            @Override
                            public int getLayoutId(int viewType) {
                                return R.layout.item_img_recycler3;
                            }

                            @Override
                            public void onBind(BaseViewHolder holder, final int position2) {
                                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(list.get(position).getImg().get(position2), holder.getImageView(R.id.img));


                                //  x.image().bind(holder.getImageView(R.id.img), info1.get(position).getImg().get(position2));
                                holder.getView(R.id.img).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent(activity, ShowImageDetail.class);
                                        intent.putStringArrayListExtra("paths", (ArrayList<String>) list.get(position).getImg());
                                        intent.putExtra("index", position2);
                                        startActivity(intent);
                                    }
                                });
                            }
                        });
                        break;
                    default:
                        img1.setVisibility(View.GONE);
                        line2.setVisibility(View.GONE);
                        line3.setVisibility(View.GONE);
                        line4.setVisibility(View.VISIBLE);
                        line4.setLayoutManager(new GridLayoutManager(activity, 3, LinearLayoutManager.VERTICAL, false));
                        line4.setAdapter(new BaseRVAdapter(activity, list.get(position).getImg()) {
                            @Override
                            public int getLayoutId(int viewType) {
                                return R.layout.item_img_recycler3;
                            }

                            @Override
                            public void onBind(BaseViewHolder holder, final int position2) {
                                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(list.get(position).getImg().get(position2), holder.getImageView(R.id.img));


                                //  x.image().bind(holder.getImageView(R.id.img), info1.get(position).getImg().get(position2));
                                holder.getView(R.id.img).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent(activity, ShowImageDetail.class);
                                        intent.putStringArrayListExtra("paths", (ArrayList<String>) list.get(position).getImg());
                                        intent.putExtra("index", position2);
                                        startActivity(intent);
                                    }
                                });
                            }
                        });
                        break;
                }

            }


        };
        // loadadapter.addHeaderView(headview);
        recycler.setAdapter(loadadapter);
        //
        head.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false));

        //
//        upLoad(0, "0", 0);
        recycler.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {

            @Override
            public void onRefresh() {
                upLoad(0, type, 0);
            }

            @Override
            public void onLoadMore() {
                upLoad(1, type, 0);
            }
        });
//
        upTitle();
    }

    private void upTitle() {
        Map<String, Object> map = new HashMap<>();
        activity.showDialog();

        XUtil.Post(Url.DECORATE_INSTALLRECEIVECATE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----title", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        Gson g = new Gson();
                        OrderImgBean b = g.fromJson(result, OrderImgBean.class);
                        setData(b.getInfo());
                        if (b.getInfo().size() > 0)
                            upLoad(0, b.getInfo().get(0).getPid(), 0);
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                            activity.MyToast(info);
                        }
                        //  activity.MyToast(info);


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                activity.closeDialog();
                recycler.setPullLoadMoreCompleted();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                activity.closeDialog();
                ex.printStackTrace();
            }
        });


    }

    private void jiedan(String orderid, final int position) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("orderid", orderid);
        activity.showDialog();

        XUtil.Post(Url.DECORATE_RECEIVEORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        activity.MyToast(info);
                        list.get(position).setJiedan(1);
                        loadadapter.notifyDataSetChanged();

                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        activity.MyToast(info);
                        if (info.contains("罚款")) {
                            activity.showDialogv7("是否去交罚款?", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    startActivity(new Intent(activity, YanShou2FaActivity.class));
                                }
                            });
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                recycler.setPullLoadMoreCompleted();
                activity.closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                activity.closeDialog();
                ex.printStackTrace();
            }
        });


    }

    private String type = "0";
    private BaseRVAdapter headadapter, loadadapter;


    private List<Home1OrderBean.InfoEntity> list = new ArrayList<>();
    private int page = 0;

    private void upLoad(final int i, String type, final int isupload) {
        Map<String, Object> map = new HashMap<>();
        if (MyApplication.getInstance().getUserBean() == null) {
            return;
        }
        if (i == 0) {
            page = 0;
        } else {
            page++;
        }
        map.put("type", type);
        map.put("token",MyApplication.getInstance().getUserBean().getToken());
        map.put("page", page);
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, "" + value + "\n");
            }
        }
        XUtil.Post(Url.DECORATE_INSTALLRECEIVELIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LogUtil.e("----ooo", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        Home1OrderBean bean = gson.fromJson(result, Home1OrderBean.class);
                        List<Home1OrderBean.InfoEntity> list1 = bean.getInfo();
                        if (i == 0) {
                            list.clear();
                        }
                        list.addAll(list1);
                        loadadapter.notifyDataSetChanged();
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                            //    activity.MyToast(info);
                            activity.MyToast(info);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                recycler.setPullLoadMoreCompleted();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                recycler.setPullLoadMoreCompleted();
                ex.printStackTrace();
            }
        });


    }

    private void setData(final List<OrderImgBean.InfoEntity> img) {
        headadapter = new BaseRVAdapter(activity, img) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_img;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                ImageLoader.getInstance().displayImage(img.get(position).getImg(), holder.getImageView(R.id.img));
                holder.setTextView(R.id.text, img.get(position).getLabel());
                holder.getView(R.id.img).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        type = img.get(position).getPid();
                        upLoad(0, img.get(position).getPid(), 1);
                    }
                });
            }


        };
        head.setAdapter(headadapter);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Constants.LOGO_SUCCESS)) {
            upTitle();
        }

    }
}
